<template>
	<view class="count">{{ count }}</view>
</template>

<script>
	export default {
		name:"count-to",
		props:{
			start:{
				type:Number,
				default:0
			},
			end:{
				type:Number,
				default:100
			},
			duration:{
				type:Number,
				default: 3000
			}
		},
		data() {
			return {
				count:0,
				speed:10
			};
		},
		created(){
			this.startAnimation();
		},
		methods:{
			startAnimation(){
				if(this.end == 0) return
				let arr = this.end.toString().split('.')
				let decimals = arr.length > 1 ? arr[1].length : 0
				let times = this.duration/this.speed
				
				var step = (this.end - this.start) / times;
				let i = 0;
				let time = setInterval(()=> {
					this.count = parseFloat((this.start + step * i)).toFixed(decimals);
					if (times == i) {
						clearInterval(time);
					}
					i++;
				}, this.speed)			
				
			}
		},
		watch: {
			end(newVal, oldVal) {
				if(newVal == 0) return this.count = 0
				this.start = oldVal;
				this.startAnimation();
			}
		}
	}
</script>

<style lang="scss">

</style>
